package com.nariano.webapp.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class ResourceNameShuffler {
    
    @Autowired
    @Qualifier(value="imageResources")
    private Properties properties;
    
    private Map<String, Entry> resources;

    
    public String getResourceName(String key) {
        return resources.get(key).getRandom();
    }
    
    public void setResource(Properties properties) {
        this.properties = properties;
    }
    
    public final void afterPropertiesSet() {
        
        fill("field.conflict");
        fill("forrest.conflict");
        fill("mountain.conflict");
        fill("sea.conflict");
        
    }

    private void fill(String key) {
        if (resources.containsKey(key)) throw new IllegalStateException("Key already in map " + key);
        Entry entry = new Entry();
        resources.put(key, entry);
        
        if (properties.containsKey(key + ".count")) {
            int count = Integer.valueOf(properties.getProperty(key + ".count"));
            for (int i = 0; i<count; i++) {
                entry.add(properties.getProperty(key + "." + i));
            }
        } else {
            entry.add(properties.getProperty(key));
        }
    }
    
    private class Entry {
        int size;
        List<String> images = new ArrayList<String>();
        
        public void add(String value) {
            images.add(value);
            size++;
        }

        public String getRandom() {
            return images.get(new Random().nextInt(size));
        }
    }
    

}
